using B.S.XZYData.Api.Wrter.Application.Command.ZSH;
using B.S.XZYData.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Net.Mime;

namespace B.S.XZYData.Api.Wrter.Controllers
{
	/// <summary>
	/// 不良品项写入接口
	/// </summary>
	[ApiController]
	[Route("api/[controller]/[action]")]
	public class DefectiveController : ControllerBase
	{
		private readonly IMediator _mediator;
		public DefectiveController(IMediator mediator) { _mediator = mediator; }

		/// <summary>
		/// 新增不良品项
		/// </summary>
		[HttpPost]
		public Task<ApiResult<int>> Add([FromBody] AddDefectiveCommand request)
		{
			return _mediator.Send(request);
		}

		/// <summary>
		/// 批量删除不良品项（伪删除）
		/// </summary>
		[HttpDelete]
		public Task<ApiResult<int>> DeleteBatch([FromBody] DeleteDefectiveBatchCommand request)
		{
			return _mediator.Send(request);
		}

		/// <summary>
		/// 编辑不良品项
		/// </summary>
		[HttpPut]
		public Task<ApiResult<int>> Update([FromBody] UpdateDefectiveCommand request)
		{
			return _mediator.Send(request);
		}

		/// <summary>
		/// 导入不良品项（NPOI）
		/// </summary>
		[HttpPost]
		public Task<ApiResult<int>> Import([FromForm] ImportDefectiveCommand request)
		{
			return _mediator.Send(request);
		}

		/// <summary>
		/// 导出不良品项（无样式 Excel）
		/// </summary>
		[HttpGet]
		public async Task<FileContentResult> Export([FromQuery] ExportDefectiveQuery query)
		{
			var bytes = await _mediator.Send(query);
			return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "不良品项导出.xlsx");
		}

        /// <summary>
        /// 获取导入模板（中文表头，无样式）：Excel 与 CSV
        /// </summary>
        [HttpGet]
        public IActionResult DownloadTemplate([FromQuery] string type = "xlsx")
        {
            if (type.ToLower() == "csv")
            {
                var csv = "不良品项编号,不良品项名称,附件路径,图片路径\n";
                var bytes = System.Text.Encoding.UTF8.GetBytes(csv);
                return File(bytes, "text/csv; charset=utf-8", "不良品导入模板.csv");
            }

            // xlsx
            using var ms = new System.IO.MemoryStream();
            var wb = new NPOI.XSSF.UserModel.XSSFWorkbook();
            var sheet = wb.CreateSheet("模板");
            var header = sheet.CreateRow(0);
            header.CreateCell(0).SetCellValue("不良品项编号");
            header.CreateCell(1).SetCellValue("不良品项名称");
            header.CreateCell(2).SetCellValue("附件路径");
            header.CreateCell(3).SetCellValue("图片路径");
            wb.Write(ms);
            return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "不良品导入模板.xlsx");
        }
    }
}


